<template>
  <el-form ref="postForm" :model="postForm" :rules="rules">
    <div style="padding: 40px 45px 20px 50px;">
      <el-row>
        <el-col :span="14">
          <el-form-item label="标题" prop="name">
            <el-input v-model.trim="postForm.name" />
          </el-form-item>
          <el-form-item label="序号">
            <el-input v-model.trim="postForm.sequence" />
          </el-form-item>
        </el-col>
        <el-col :span="10">
          <el-form-item label="轮播图(尺寸:340 * 160):" prop="image" style="margin-left: 30px;">
            <Upload :default-image.sync="postForm.image" :mode="6" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item>
        <el-card class="box-card" shadow="hover">
          <div slot="header" class="clearfix">
            <span>轮播图商品</span>
            <el-button v-if="selectGoodList.length == 0" style="float: right; padding: 3px 0" type="text" @click="addProduct()">添加商品</el-button>
          </div>
          <el-table :data="selectGoodList" fit highlight-current-row row-key="id" style="width: 100%;">
            <el-table-column label="商品编号" prop="identifier" align="center" />
            <el-table-column label="商品名称" prop="name" align="center" />
            <el-table-column label="商品分类" prop="categoryName" align="center" />
            <el-table-column label="供货供应商" prop="splitSupplier" align="center" />
            <el-table-column label="定价" prop="priceText" align="center" />
            <el-table-column label="库存" prop="store" align="center" />
            <el-table-column label="商品类型" prop="isSeckillText" align="center" />
            <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
              <template slot-scope="{row}">
                <el-button type="danger" size="mini" @click="handleDeleteGood(row)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="submit" >确定</el-button>
      </el-form-item>

      <el-dialog title="商品列表" :close-on-click-modal="false" :visible.sync="dialogVisible" width="1000px">
        <div class="filter-container">
        <el-input v-model="goodsListQuery.identifier$lk" placeholder="商品编号" class="filter-item" clearable/>
        <el-input v-model="goodsListQuery.name$lk" placeholder="商品名称" class="filter-item" clearable/>
        <el-button v-waves class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter">
          查询
        </el-button>
      </div>
        <el-table :data="goodsList" border fit highlight-current-row row-key="id" style="width: 100%;" :max-height="400">
          <el-table-column label="商品编号" prop="identifier" align="center" />
          <el-table-column label="商品名称" prop="name" align="center" />
          <el-table-column label="商品分类" prop="categoryName" align="center" />
          <el-table-column label="供货供应商" prop="splitSupplier" align="center" />
          <el-table-column label="定价" prop="priceText" align="center" />
          <el-table-column label="库存" prop="store" align="center" />
          <el-table-column label="商品类型" prop="isSeckillText" align="center" />
          <el-table-column label="审核状态" align="center">
            <template slot-scope="{row}">
              <el-tag :type="row.status | statusFilter">
                {{ returnValueToLable(row.status,statusJson) }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width" fixed="right">
            <template slot-scope="{row}">
              <el-button type="primary" size="mini" @click="handleSelect(row)">
                入选
              </el-button>
            </template>
          </el-table-column>
        </el-table>
        <Pagination v-show="goodsTotal>0" :total="goodsTotal" :page.sync="goodsListQuery.pageNo" :limit.sync="goodsListQuery.pageSize"
        @pagination="getGoodsList" />

        <div slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">
            确定
          </el-button>
        </div>
      </el-dialog>
    </div>
  </el-form>
</template>

<script>
import Tinymce from '@/components/Tinymce'
import Upload from '@/components/Upload'
import { newsSave, newsGetById } from '@/api/website'
import { productPageByQo, productGetById } from '@/api/product'
import waves from '@/directive/waves' // waves directive
import Pagination from '@/components/Pagination'

const defaultForm = {
  id: 0,
  sequence: '',
  code: "zcyxIndexRoll",
  productId: '',
  identifier: '',
  image: '',
  name: '',
  num: '',
  remark: '',
  paramType: 99,
}
export default {
  name: 'ZcyxIndexRollSave',
  directives: { waves },
  components: { Tinymce, Upload, Pagination },
  filters: {
    statusFilter(status) {
      const statusMap = {
        0: 'danger',
        1: 'success',
        2: '',
        3: 'info'
      }
      return statusMap[status]
    }
  },
  props: {
  },
  data() {
    return {
      postForm: Object.assign({}, defaultForm),
      rules: {
        image: [{ required: true, message: '请选择', trigger: 'blur' }],
        name: [{ required: true, message: '请输入', trigger: 'blur' }],
        remark: [{ required: true, message: '请输入图文详情', trigger: 'blur' }],
      },
      isEdit: false,
      selectGoodList: [],
      dialogVisible: false,
      statusJson: [
        {
          value: '1',
          label: '正常'
        }, {
          value: '0',
          label: '下线'
        }
      ],
      goodsList: [],
      goodsTotal: 0,
      goodsListQuery: {
        type: 4,
        isSeckill$in: '1,0',
        identifier$lk: '',
        name$lk: '',
        status: "1",
        pageNo: 1,
        pageSize: 20
      },
    }
  },
  created() {
    this.init()
  },
  methods: {
    init() {
      this.isEdit = this.$route.query && this.$route.query.id && Number(this.$route.query.id) > 0
      if (this.isEdit) {
        this.fetchData(this.$route.query.id)
      }
    },
    getProduct(id) {
      productGetById({ id: id }).then(response => {
        this.selectGoodList.push(response)
      }).catch(err => {
        console.log(err)
      })
    },
    fetchData(id) {
      newsGetById(id).then(response => {
        this.postForm = Object.assign({}, response)
        if (this.postForm.remark) {
          this.$refs.editor.setContent(this.postForm.remark)
        }

        if(this.postForm.productId && Number(this.postForm.productId) > 0) {
          this.getProduct(this.postForm.productId)
        }
      }).catch(err => {
        console.log(err)
      })
    },
    addProduct() {
      this.goodsListQuery.pageNo = 1
      productPageByQo(this.goodsListQuery).then(response => {
        this.goodsList = response.list || []
        this.goodsTotal = response.totalCount
        this.dialogVisible = true
      })
    },
    handleFilter() {
      this.goodsListQuery.pageNo = 1
      this.getGoodsList()
    },
    getGoodsList() {
      productPageByQo(this.goodsListQuery).then(response => {
        this.goodsList = response.list || []
        this.goodsTotal = response.totalCount
      })
      .catch((err) => {
        console.log(err)
        this.listLoading = false
      })
    },
    handleSelect(row) {
      if (this.selectGoodList.length == 0) {
        this.selectGoodList.splice(this.selectGoodList.length, 1, row)
      } else {
        var flag = false
        for (let index = 0; index < this.selectGoodList.length; index++) {
          const element = this.selectGoodList[index];
          if (row.id == element.id) {
            flag = true
          }
        }
        
        if (flag) {
          this.$message.error("已选择");
        } else {
          this.selectGoodList.splice(this.selectGoodList.length, 1, row)
        }
      }

      this.dialogVisible = false
    },
    handleDeleteGood(row) {
      for (let index = 0; index < this.selectGoodList.length; index++) {
        const element = this.selectGoodList[index];
        if (row.id == element.id) {
          this.selectGoodList.splice(index,1);
          return 
        }
      }
    },
    submit() {
      this.$refs['postForm'].validate((valid) => {
        if (valid) {
          let params = Object.assign({}, this.postForm)
          delete params.createTime

          if (this.selectGoodList.length > 0) {
            params.productId = this.selectGoodList[0].id
          } else {
            params.productId = ""
          }

          newsSave(params, this.isEdit).then((res) => {
            this.$notify({
              title: '成功',
              message: `${this.isEdit ? '编辑' : '添加'}成功`,
              type: 'success',
              duration: 2000
            })
            // 调用全局挂载的方法,关闭当前标签页
            this.$store.dispatch("tagsView/delView", this.$route);
            this.$router.push({
              path: '/zcyx/zcyxIndexRoll',
              query: {
                t: Date.now()
              }
      });
          })
        }
      })
    }
  }
}
</script>
<style lang="scss" scoped>

</style>